<template>
     <div class="rightBoxContainer">
          <div class="searchBox">
               <page-search
                    pageName="pages_container"
                    v-if="searchFormConfigRef"
                    ref="pageSearchRef"
                    :searchConfig="searchFormConfigRef"
                    @queryBtnClick="handleQueryClick"
                    @resetBtnClick="handleResetClick"
                    @searchChange="searchChange">
                    <template #button>
                         <div v-if="isUserMangeShow" style="position: absolute; right: 0; top: 40%; transform: translateY(-50%)">
                              <el-button @click="handleNewData" type="primary">新增</el-button>
                              <el-button @click="exportBtn" type="primary">导出</el-button>
                         </div>
                    </template>
               </page-search>
          </div>
          <div class="tableBox">
               <page-content
                    v-if="contentTableConfigRef"
                    ref="pageContentRef"
                    :tableLoading="tableLoading"
                    pageName="pages_container"
                    :contentConfig="contentTableConfigRef"
                    @getTableList="getTableList"
                    @editBtnClick="handleEditData"
                    @delBtnClick="handleDelData"
                    @getSelectionData="getSelectionData"
                    :deleteBtnShow="isUserMangeShow"
                    :editBtnShow="isUserMangeShow"
                    :showHandle="false">
                    <template #btns></template>
               </page-content>
          </div>
          <page-modal
               v-if="modalConfigRef"
               ref="pageModalRef"
               :modalConfig="modalConfigRef"
               :defaultInfo="modalInfo"
               pageName="pages_container"
               @addSuccess="addSuccess"
               @editSuccess="editSuccess"></page-modal>
     </div>
</template>

<script setup lang="ts">
import pageContent from '@/components/pageContent'
import pageSearch from '@/components/pageSearch'
import pageModal from '@/components/pageModal'
import { usePageTable } from '@/hooks/table/usePageTable'
import { contentTableConfig, emptyTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'
import { GetUsers, AddUser, UpdateUser, DeleteUser } from '@/api/userManagement'
import { GetDistrictsByLevelAndName, GetLineList } from '@/api/common'
import { ElMessage } from 'element-plus'
import * as rule from '@/utils/rule'
import { download } from '@/utils/exportFile'
import useUserStore from '@/store/modules/user'
let useStore = useUserStore()
let props = defineProps({
     chartData: {
          type: Object as PropType<any>,
     },
})
const userPermission = computed(() => {
     return useStore.userInfoData.permission?.split(',') ?? []
})
const isUserMangeShow = computed(() => {
     return userPermission.value.includes('用户管理') ?? false
})

const newHandleCallback = async (val: any) => {
     modalConfigRef.value.formItems.forEach((item: any) => {
          if (item.field === 'password') {
               item.rules = [
                    rule.cannotBeEmpty('请输入用户密码'),
                    rule.limitContinuousSymbol(6),
                    rule.limitContinuousLettersOrNumbers(6),
                    rule.limitLengthInterval(10, 30),
                    rule.limitPasswordFormat,
               ]
          }
     })
     nextTick(() => {
          pageModalRef.value && pageModalRef.value.dialogColse()
     })
}
const editHandleCallback = async (val: any) => {
     modalConfigRef.value.formItems.forEach((item: any) => {
          if (item.field === 'password') {
               item.rules = [
                    rule.limitContinuousSymbol(6),
                    rule.limitContinuousLettersOrNumbers(6),
                    rule.limitLengthInterval(10, 30),
                    rule.limitPasswordFormat,
               ]
          }
     })
     let district = [val.province, val.city, val.conty, val.village]
     // 从后往前循环判断 省市县镇是否为空
     for (let i = district.length - 1; i >= 0; i--) {
          if (district[i]) {
               break
          }
          district.pop()
     }
     modalInfo.value = {
          ...val,
          district: district[district.length - 1] ?? '',
          permission: val.permission ? val.permission.split(',') : [],
          xlqx: val.xlqx ? val.xlqx.split(',') : [],
     }
}
// 单个删除方法回调
const delHandleCallback = async (val: any) => {
     try {
          let obj = {
               userid: val ?? modalInfo.value.userid,
          }
          const res: any = await DeleteUser(obj)
          const message = res == '删除成功' ? '删除成功' : '删除失败'
          ElMessage({
               type: res == '删除成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const {
     searchFormConfigRef,
     contentTableConfigRef,
     modalConfigRef,
     pageModalRef,
     pageContentRef,
     pageSearchRef,
     modalInfo,
     tableLoading,
     selectCheckData,
     permissionRef,
     handleOnSuccess,
     handleNewData,
     handleEditData,
     handleDelData,
     handleQueryClick,
     handleResetClick,
     getSelectionData,
     templateDownloadClick,
     hasPermission,
} = usePageTable(newHandleCallback, editHandleCallback, null, delHandleCallback)
onMounted(async () => {
     await getSelectOptions()
     contentTableConfigRef.value = contentTableConfig
     searchFormConfigRef.value = searchFormConfig
     modalConfigRef.value = modalConfig
     nextTick(() => {
          pageSearchRef.value?.handleResetClick()
     })
})
const searchChange = (data: any) => {
     console.log('searchChange', data)
}

const getTableList = async (params: any) => {
     try {
          const requestParams = {
               ...params,
               ...props.chartData,
          }
          tableLoading.value = true
          const tabelData: any = await GetUsers(requestParams)
          tableLoading.value = false
          const newData = tabelData.Data || []
          const newTotal = Number(tabelData.Count) || 0
          nextTick(() => {
               if (newData.length > 0) {
                    pageContentRef.value!.setTableData(newData, newTotal)
               } else {
                    pageContentRef.value!.setTableData([], 0)
               }
          })
     } catch (error) {
          tableLoading.value = false
          console.error('Failed to get table data:', error)
     }
}

const findPathToNode = (tree: any[], targetLabel: string, currentPath: any[] = []): any[] | null => {
     for (const node of tree) {
          if (!node.Name) {
               continue // 跳过空标签的节点
          }
          const newPath = [...currentPath, node]
          if (node.Name === targetLabel) {
               return newPath
          }
          if (node.SubDistricts && node.SubDistricts.length > 0) {
               const result = findPathToNode(node.SubDistricts, targetLabel, newPath)
               if (result) {
                    return result
               }
          }
     }
     return null
}

const formatAddAndEditData = (data: any) => {
     let activeData = Array.isArray(data.district) ? data.district[data.district.length - 1] : data.district
     let path: any = findPathToNode(districtList.value, activeData)
     disname.value = path[path.length - 1].Name ?? ''
     dislevel.value = path[path.length - 1].Unit ?? ''
     let district = {
          province: '',
          city: '',
          conty: '',
          village: '',
     }
     if (path) {
          path.forEach((node: any) => {
               switch (node.Unit) {
                    case '省':
                         district.province = node.Name
                         break
                    case '市':
                         district.city = node.Name
                         break
                    case '县':
                         district.conty = node.Name
                         break
                    case '乡':
                         district.village = node.Name
                         break
                    default:
                         break
               }
          })
     }
     return {
          ...data,
          ...district,
     }
}
const disname = ref('')
const dislevel = ref('')

// 新增的回调方法
const addSuccess = async (val: any) => {
     try {
          disname.value = ''
          dislevel.value = ''
          let obj = {
               ...formatAddAndEditData(val),
               permission: val.permission.join(','),
               xlqx: val.xlqx.join(','),
               disname: disname.value,
               dislevel: dislevel.value,
          }

          delete obj.district
          const res: any = await AddUser(obj)
          const message = res == '添加成功' ? '添加成功' : '添加失败'
          ElMessage({
               type: res == '添加成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}

// 编辑的回调方法
const editSuccess = async (val: any) => {
     try {
          disname.value = ''
          dislevel.value = ''
          let obj = {
               ...formatAddAndEditData(val),
               permission: val.permission.join(','),
               xlqx: val.xlqx.join(','),
               disname: disname.value,
               dislevel: dislevel.value,
          }
          delete obj.district
          if (!obj.password) delete obj.password
          const res: any = await UpdateUser(obj)
          const message = res == '修改成功' ? '编辑成功' : '编辑失败'
          ElMessage({
               type: res == '修改成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const districtList = ref([])
const lineList = ref([])
// 获取对应选择器的下拉选项
const getSelectOptions = async () => {
     try {
          const res = await GetDistrictsByLevelAndName()
          const res1 = await GetLineList()
          modalConfig.formItems.forEach((item: any) => {
               if (item.field === 'district') {
                    item.cascader = Array.isArray(res) ? res : []
                    districtList.value = item.cascader
               } else if (item.field === 'xlqx' && res1 && Array.isArray(res1)) {
                    item.options = res1.map((item: any) => {
                         return {
                              label: item.xlname,
                              value: item.xlname,
                         }
                    })
                    lineList.value = item.options
               }
          })
     } catch (error) {
          console.error(error)
     }
}
const exportBtn = () => {
     download(null, 'excels', `用户列表_${new Date().toLocaleDateString()}.xlsx`)
}
watch(
     () => props.chartData,
     () => {
          pageSearchRef.value?.handleQueryClick()
     },
     { deep: true },
)
</script>

<style lang="scss" scoped>
.rightBoxContainer {
     width: 100%;
     height: 100%;
     display: flex;
     flex-direction: column;
     overflow: auto;
     padding-right: 5px;

     .titleBox {
          width: 100%;
          height: 5%;
          color: #fff;
          font-weight: bold;
          font-size: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #0a3e6e;
          border-radius: 5px;
     }

     .searchBox {
          width: 100%;
          height: auto;
     }

     .tableBox {
          height: 80%;
          width: 100%;
          border-radius: 10px;
     }
}
</style>
